package com.smart4j.chapter.modules.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.smart4j.chapter.modules.web.FileListServlet;

/**
 * 文件下载 servlet
 */
@WebServlet("/downloadServlet")
public class DownLoadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	

    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownLoadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 1、获取下载文件名
		String fileName = request.getParameter("fileName");
	//	fix: GET请求中文乱码， 因Tomcat默认编码为 ISO-8859-1 
	//  彻底解决办法： tomcat的话可以在 server.xml 文件里指定编码格式为UTF-8。Connector 添加： URIEncoding=”UTF-8” 2019年9月2日 21:40:42
	//	fileName = new String(fileName.getBytes("ISO-8859-1"),"UTF-8");
		File[] fileList = FileListServlet.fileList;
		for (File file : fileList) {
			if(fileName.equals(file.getName())){
				
				response.reset();
				response.setCharacterEncoding("UTF-8");
				fileName = URLEncoder.encode(fileName, "UTF-8");
				// 标记响应文件 流文件
				response.setContentType("application/octet-stream");
				response.setHeader("Content-Disposition", "attachment;fileName="+fileName);
				InputStream input = new FileInputStream(file);
				ServletOutputStream out = response.getOutputStream();
				byte[]  buff =new byte[1024];
				int len ;
				while((len = input.read(buff)) != -1){
					out.write(buff, 0, len);
					out.flush();
				}
				input.close();
				out.close();
			}
		}
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
